--
-- Author: yawei.zhu
-- Date: 2018-12-15 15:03:01
--
-- PvpChallengeController
--
local PvpChallengeMatchView = import("..views.PvpChallengeMatchView")
local PvpChallengeNoticeView = import("..views.PvpChallengeNoticeView")
local PvpChallengeBookView = import("..views.PvpChallengeBookView")
local PvpChallengeRankAwardView = import("..views.PvpChallengeRankAwardView")
local PvpChallengeMatchingView = import("..views.PvpChallengeMatchingView")

local fileName = string.getModeName(...)
local ClassRef = class(fileName, app.mvc.ControllerBase)

function ClassRef:ctor(data)
    self.super.ctor(self, data)
end

function ClassRef:init()
    self._model = app:getInst("PvpModel")
    self._teamModel = app:getInst("TeamModel")
end

function ClassRef:removeListeners()
    self.super.removeListeners(self)
end

function ClassRef:listEvent()
    return {
        "onCreateTeam",
        "onJoinTeam",
        "onTeamUpdate",
        "onTeamMemberUpdate",
        "onTeamLeaderChanged",
        "onTeamSettingUpdate",
        "onTeamNewApplyer",
        "onChallengeMatchChange",
    }
end

function ClassRef:onEvent(eventName, data)
    if eventName == "onCreateTeam" then
        -- 加入队伍
        self:updateAutoRecruit()
        self:updateAutoApply()
    elseif eventName == "onJoinTeam" then -- 队伍更新
        self:updateAutoRecruit()
        self:updateAutoApply()
    elseif eventName == "onTeamUpdate" then -- 队伍更新
        self:refreshTeam()
    elseif eventName == "onTeamMemberUpdate" or
        eventName == "onTeamLeaderChanged" then
        self:refreshMember()
    elseif eventName == "onTeamSettingUpdate" then -- 队伍设置更新
        self:updateAutoRecruit()
    elseif eventName == "onTeamNewApplyer" then -- 来新申请人
        if self._teamModel:isMyTeam() then
            self._teamModel:reqGetApplicationList()
        end
        self:refreshApplyNew()
    elseif eventName == "onChallengeMatchChange" then -- 挑战赛匹配更改
        self:refreshTeam()
    end

end

-- open挑战赛匹配界面
function ClassRef:openView(data)
    if cc.isDead(self._view) then
        self._view = PvpChallengeMatchView.new(app.mvc.VIEWTYPE_BLUR)
        self._view:onCloseView(handler(self, self.closeView))
        self._view:onClearView(handler(self, self.clearView))
        self._view:onOperate(handler(self, self.onOperate))
    end
    self:addChild(self._view, data)

    local challengeInfo = self._model:getChallengeInfo()
    if challengeInfo then
        self._view:refreshChallengeInfo(challengeInfo)
        self._view:refreshTarget(challengeInfo:getTeamTarget())
        self:refreshTeam()
    else
        self._model:reqChallengeInfo()
    end
    self._view:show()
end
function ClassRef:clearView()
    if self._view then
        self._view = nil
    end
end

function ClassRef:isChallengeShow()
    return self:isViewVisible()
end

-------------------------------------------------------
-- 挑战赛介绍界面
function ClassRef:openChallengeNoticeView(challengeInfo)
    local view = PvpChallengeNoticeView.new()
    view:onCloseView(function()
        UIHandler:removePopupUiByKey(view:getViewName())
    end)
    view:onOperate(handler(self, self.onOperate))
    UIHandler:addPopupUi(view, view:getViewName())
    view:show()
    view:updateView(challengeInfo)
end

-- 挑战赛bookview
function ClassRef:openChallengeBookView(playId)
    local view = PvpChallengeBookView.new(app.mvc.VIEWTYPE_BLUR)
    view:onCloseView(function()
        UIHandler:removeSystemUiByKey(view:getViewName())
    end)
    view:onOperate(function(op, data)
        if op == "showChallengeRankAward" then
            self:openChallengeRankAward(data)
        end
    end)
    UIHandler:addSystemUi(view, view:getViewName())
    view:show()
    view:updateView(playId)
end

-- 挑战赛排行奖励
function ClassRef:openChallengeRankAward(playId)
    local view = PvpChallengeRankAwardView.new()
    view:onCloseView(function()
        UIHandler:removePopupUiByKey(view:getViewName())
    end)
    UIHandler:addPopupUi(view, view:getViewName())
    view:updateView(playId)
    view:show()
end

-- 挑战赛准备UI
function ClassRef:updateChallengePrepare(msg)
    if cc.isDead(self._prepareView) then
        local view = PvpChallengeMatchingView.new(app.mvc.VIEWTYPE_BLUR)
        view:onCloseView(function()
            -- UIHandler:removeSystemUiByKey(view:getViewName())
            UIHandler:removePopupUiByKey(view:getViewName())
            self._prepareView = nil
        end)
        view:onClearView(function()
            self._prepareView = nil
        end)
        view:onOperate(handler(self, self.onOperate))
        -- UIHandler:addSystemUi(view, view:getViewName())
        UIHandler:addPopupUi(view, view:getViewName())
        view:show()
        self._prepareView = view
    end

    if not msg then
        msg = self._model:getChallengePrepareNotify()
    end
    local endTime = self._model:getChallengePrepareEndTime()
    if msg.playId == Enums.TeamTarget.eliteMatchArena or
     msg.playId == Enums.TeamTarget.eliteMatchDuel then -- 跨服精英赛公用准备UI
        endTime = UD.csEliteMatch:getCrossCombatPrepareEndTime()
    end
    self._prepareView:updateView(msg, endTime)
end

-- 挑战赛 关闭准备UI
function ClassRef:closeChallengePrepare()
    if not cc.isDead(self._prepareView) then 
        -- UIHandler:removeSystemUiByKey(self._prepareView:getViewName())
        UIHandler:removePopupUiByKey(self._prepareView:getViewName())
        self._prepareView = nil
    end
end

-------------------------------------------------------
-- 打开挑战赛 赛季等级 提升界面
function ClassRef:openChallengeLevelView(seasonId, endTime, lv)
    local view = PvpLevelView.new()
    view:onCloseView(function(sender)
        UIHandler:removePopupUiByKey(sender:getViewName())
    end)
    view:refreshChallenge(seasonId, endTime, lv)
    UIHandler:addPopupUi(view, view:getViewName())
    view:show()
end

-------------------------------------------------------
-- 挑战赛信息更新
function ClassRef:onChallengeInfoUpdate(challengeInfo)
    if not self:isViewAlive() then return end

    self._view:refreshChallengeInfo(challengeInfo)
    self._view:refreshTarget(challengeInfo:getTeamTarget())

    -- 检查赛季等级是否有提升
    if self._oldChallengeLv and self._oldChallengeLv > challengeInfo.lv then -- 等级降低时，弹出提示框
        self:openChallengeLevelView(challengeInfo.id, challengeInfo.endTime, challengeInfo.lv)
    end
    self._oldChallengeLv = challengeInfo.lv

    -- 检查是否是新赛季
    local lastShowTime = UD.setting:getLastChallengeTipShowTime()
    -- print("challengeTime:", lastShowTime, challengeInfo.startTime, app.session:getServerTime())
    if lastShowTime < challengeInfo.startTime then
        self:openChallengeNoticeView(challengeInfo)
        UD.setting:setLastChallengeTipShowTime(math.floor(app.session:getServerTime()))
    end

    -- 检查是否有赛季宝箱
    if not challengeInfo.LastRewarded and challengeInfo.LastParticipated then
        app:sendMsg("BoxController", "openView", {boxType = Enums.BoxType.challengeSeason, seasonLv = challengeInfo.LastLevel})
    end
end

-- 队伍更新
function ClassRef:refreshTeam()
    if not self:isViewAlive() then return end

    local team = self._teamModel:getTeam()
    self._view:refreshTeam(team)

    local challengeInfo = self._model:getChallengeInfo()
    if not challengeInfo then return end

    local target = challengeInfo:getTeamTarget()
    local isInCrossMatch = target:isInCrossMatch()
    if not isInCrossMatch and not team then
        -- 组队玩法和开放的玩法，没有队伍时需要去拉队伍
        local isSingle = target:isSingle()
        local isOpen = target:isOpen()
        local isTimeOpen, _ = target:checkTimeOpen()
        if not isSingle and isOpen and isTimeOpen then
            self._teamModel:C2S_GetTeamList(target.id)
        else
            self:refreshTeamList({})
        end
    end
end

-- 刷新申请状态
function ClassRef:refreshApplyNew()
    if not self:isViewAlive() then return end
    self._view:refreshApplyNew(self._teamModel:isNewApplyerFlag())
end

-- 我的队伍刷新
function ClassRef:refreshMember()
    if not self:isViewAlive() then return end

    self._view:refreshMember()
end

-- 刷新推荐队伍
function ClassRef:refreshTeamList(teamList)
    if not self:isViewAlive() then return end
    self._view:refreshTeamList(teamList)
end

-- 刷新推荐队伍里面的申请状态
function ClassRef:refreshTeamListApply(team)
    if not self:isViewAlive() then return end

    self._view:refreshTeamListApply(team)
end

-- 更新自动申请
function ClassRef:updateAutoApply()
    if not self:isViewAlive() then return end

    self._view:updateAutoApplyStatus()
end

-- 更新自动招募
function ClassRef:updateAutoRecruit()
    if not self:isViewAlive() then return end

    self._view:updateAutoRecruitStatus()
end


-- 开始挑战赛匹配
function ClassRef:startChallengeMatch(isTeam)
    if not self._model:isChallengeOpen() then
        display.pushToast(L("ErrEventNotStart"))
        return
    end

    if isTeam then
        -- 首先检查队员是否满足匹配条件
        self._model:reqCheckChallengeMatchCondition(function()
            local params = {
                idx = 1,
                targetId = Enums.TeamTarget.challenge,
                isMatch = true
            }
            app:sendMsg("NewTeamReadyAndSettingController", "openView", params)
        end)
    else
        self._model:reqChallengeMatch()
    end
end

-- 取消匹配
function ClassRef:cancelChallengeMatch()
    if not self._teamModel:isInTeam() or self._teamModel:isMyTeam() then
        self._model:reqChallengeCancelMatch()
    else
        local dlg = display.newConfirmDialog( L("CrossServerTips4"),
            function() -- 确定
                self._teamModel:reqQuitTeam()
            end)
        UIHandler:addPopDialog( dlg )
    end
end

-------------------------------------------------------
function ClassRef:onOperate(op, data)
    print("PvpChallengeController:onOperate op = " .. op)
    if op == "openBook" then -- 打开详情
        -- data = TeamTargetVo
        self:openChallengeBookView(data:getId())
    elseif op == "openRank" then
        -- data = TeamTargetVo
        local params = {id = Constant.FUNC_TYPE_RANK, mode = "open", rankingId = data:getRank()}
        UIHandler:handleMessage(params)
    elseif op == "onMatchingReady" then
        self._model:reqMatchingReady(true)
    elseif op == "onMatchingCancel" then
        self._model:reqMatchingReady(false)
    -- elseif op == "showChallengeNotice" then
        -- self:openChallengeNoticeView(data)
    elseif op == "createTeam" then -- 创建队伍
        -- data = TeamTargetVo
        app:sendMsg("TeamMatchController", "createTeam", data)
    elseif op == "changeGrade" then
        -- 修改组队性质，团队／队伍
        app:sendMsg("TeamMatchController", "changeTeamGrade")
    elseif op == "leaveTeam" then -- 离开队伍
        app:sendMsg("TeamMatchController", "leaveTeam")
    elseif op == "singleMatch" then -- 匹配
        self:startChallengeMatch(false)
    elseif op == "teamMatch" then -- 组队匹配
        self:startChallengeMatch(true)
    elseif op == "singleStart" then -- 个人匹配
        self:startChallengeMatch(false)
    elseif op == "teamStart" then -- 组队匹配
        self:startChallengeMatch(true)
    elseif op == "cancelMatch" then -- 取消匹配
        self:cancelChallengeMatch()
    elseif op == "openApply" then -- 展开申请列表
        app:sendMsg("NewTeamApplyController", "openView", { 2 } ) -- 弹出标签2-申请标签
    elseif op == "openSet" then -- 设置UI
        app:sendMsg("NewTeamSettingController", "openView")
    elseif op == "MemberInfoPanel_openInvitePanel" then -- 弹出邀请panel
        app:sendMsg("NewTeamApplyController", "openView", { 1 } ) -- 弹出标签1-邀请标签
    end 
end


return ClassRef
